//
//  ICRedPacketGroupViewController.m
//  ICome
//
//  Created by 席鹏飞 on 2016/11/8.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICRedPacketGroupViewController.h"
#import "ICRedPacketInputView.h"
#import "NSMutableAttributedString+Extension.h"
#import "ZYKeyboardUtil.h"
#import "ICRedPacketNetworkManager.h"
#import "ICRedPacketPasswordViewController.h"
#import "ICRedPacketPayPasswordView.h"
#import "ICSendRedPacketModel.h"
#import "ICRedPacketNetworkManager.h"
#import "ICHeaderFile.h"

#define AmountDigit 5   //金额位数

@interface ICRedPacketGroupViewController () <ICRedPacketPayPasswordViewDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) UILabel *redPacketPrompt;
@property (nonatomic, strong) ICRedPacketInputView *redPacketInputView;
@property (nonatomic, strong) UILabel *peoplePrompt;
@property (nonatomic, strong) ICRedPacketInputView *amountInputView;
@property (nonatomic, strong) ICRedPacketInputView *messageInputView;
@property (nonatomic, strong) UILabel *totalWorkPoint;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UILabel *bottomPrompt;
@property (nonatomic, strong) ZYKeyboardUtil *keyboardUtil;
@property (nonatomic, strong) ICRedPacketPayPasswordView *payPasswordView;
@property (nonatomic, assign) NSInteger selectedSegmentIndex;
@property (nonatomic, assign) NSInteger totalPeoples;
@property (nonatomic, strong) ICSendRedPacketModel *model;
@property (nonatomic, strong) NSString *groupId;
@end

@implementation ICRedPacketGroupViewController

- (void)dealloc {
    [self removeObserver];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.selectedSegmentIndex = 0;
    self.groupId = self.parameterDictionary[@"groupId"];
    
    [self setUI];
    [self setNav];
    [self setTap];
    [self setKeyboardUtil];
    [self getData];
    [self addObserver];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBackgroundColor:NE_REDPACKET_BACKGROUND_COLOR];
    [self setNavShadowColor:NE_REDPACKET_BACKGROUND_COLOR];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.scrollView.contentSize = CGSizeMake(self.view.width, self.bottomPrompt.bottom + 25);
}

#pragma mark - private methods

// 设置页面布局
- (void)setUI {
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.scrollView.mas_centerX);
        make.top.equalTo(self.scrollView.mas_top).offset(16);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(30);
    }];
    [self.redPacketPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segmentedControl.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(15);
    }];
    [self.redPacketInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.redPacketPrompt.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    [self.peoplePrompt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.redPacketInputView.mas_bottom).offset(5);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.mas_equalTo(15);
    }];
    [self.amountInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.peoplePrompt.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    [self.messageInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.amountInputView.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(65);
    }];
    [self.totalWorkPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.messageInputView.mas_bottom).offset(40);
        make.left.equalTo(self.messageInputView.mas_left);
        make.right.equalTo(self.messageInputView.mas_right);
        make.height.mas_equalTo(30);
    }];
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.totalWorkPoint.mas_bottom).offset(40);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(45);
    }];
    if (APP_Frame_Height == 480) {
        [self.bottomPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.sendButton.mas_bottom).offset(30);
        }];
    }else {
        [self.bottomPrompt mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.bottom.equalTo(self.view.mas_bottom).offset(-25);
        }];
    }
}
// 设置navigation
- (void)setNav {
    self.title = @"发红包";
    
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamedFromiComeSDKBundle:@"App_back_white"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)]];
}
// 设置键盘取消事件
- (void)setTap {
    WEAKSELF;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [weakSelf.view endEditing:YES];

        CGFloat height = [weakSelf.messageInputView.inputTextView.placeholder sizeWithMaxWidth:weakSelf.messageInputView.inputTextViewWidth andFont:[UIFont systemFontOfSize:16]].height;
        CGFloat textViewHeight = [weakSelf.messageInputView.inputTextView.text sizeWithMaxWidth:weakSelf.messageInputView.inputTextViewWidth andFont:[UIFont systemFontOfSize:16]].height;
        if (textViewHeight > height) {
            [weakSelf.messageInputView.inputTextView scrollToBottom];
        }
    }];
    [self.view addGestureRecognizer:tap];
}
// 设置键盘
- (void)setKeyboardUtil {
    WEAKSELF;
    self.keyboardUtil = [[ZYKeyboardUtil alloc] init];
    [self.keyboardUtil setAnimateWhenKeyboardAppearAutomaticAnimBlock:^(ZYKeyboardUtil *keyboardUtil) {
        [keyboardUtil adaptiveViewHandleWithController:weakSelf adaptiveView:weakSelf.redPacketInputView.inputTextField, weakSelf.amountInputView.inputTextField, weakSelf.messageInputView.inputTextView, nil];
    }];
}
// 网络请求
- (void)getData {
    self.redPacketInputView.contentDict = @{@"left":@"红包个数",
                                            @"right":@"个"};
    self.amountInputView.contentDict = @{@"left":@"总金额",
                                         @"right":@"工分"};
    self.messageInputView.contentDict = @{@"left":@"留言",
                                          @"right":@""};
    WEAKSELF
    [ICMessageDatabase getUsersWithGroupId:self.groupId finish:^(NSArray *array, NSError *error) {
        weakSelf.peoplePrompt.text = [NSString stringWithFormat:@"本协作群共%lu人", (unsigned long)[array count]];
        weakSelf.totalPeoples = [array count];
    }];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:self.redPacketInputView.inputTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:self.amountInputView.inputTextField];
}

- (void)removeObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)textFieldTextChanged:(NSNotification *)notification {
    UITextField *textField = notification.object;
    if ([textField isEqual:self.redPacketInputView.inputTextField]) {
        if ([textField.text intValue] > self.totalPeoples) {
            self.redPacketInputView.inputTextField.text = [NSString stringWithFormat:@"%ld", (long)self.totalPeoples];
            [MBProgressHUD showError:@"红包个数不能超过总人数"];
        }
    }else if ([textField isEqual:self.amountInputView.inputTextField]) {
        if (textField.text.length > AmountDigit) {
            self.amountInputView.inputTextField.text = [textField.text substringToIndex:AmountDigit];
        }
    }
    
    NSString *totalPoint = [self getTotalPoint:self.selectedSegmentIndex];
    self.totalWorkPoint.attributedText = [self showWorkPoint:totalPoint];

    self.sendButton.enabled = (self.redPacketInputView.inputTextField.text.length > 0 && self.amountInputView.inputTextField.text.length > 0);
    if (self.sendButton.isEnabled) {
        [self.sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:1.0] forState:UIControlStateNormal];
    }else {
        [self.sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
    }
}

// 获取总工分（判断拼手气与普通红包）
- (NSString *)getTotalPoint:(NSInteger)segmentIndex {
    NSString *totalPoint;
    if (segmentIndex == 0) {
        totalPoint = [NSString stringWithFormat:@"%.2f", [self.amountInputView.inputTextField.text floatValue]];
    } else {
        int number = [self.redPacketInputView.inputTextField.text intValue];
        totalPoint = [NSString stringWithFormat:@"%.2f", (number > 0 ? number : 1) * [self.amountInputView.inputTextField.text floatValue]];
    }
    return totalPoint;
}

- (NSMutableAttributedString *)showWorkPoint:(NSString *)point {
    NSMutableAttributedString *text = [NSMutableAttributedString attributedString:@[@"总计： ", point, @"  工分"] colors:@[ICRGB(0x000000), ICRGB(0xf65b5b), ICRGB(0x000000)] fonts:@[ICFont(16.0 * Level), ICFont(30.0 * Level), ICFont(16.0 * Level)]];
    return text;
}

- (void)pushToRedPacketPasswordViewController {
    UIViewController *viewController = [[IComMediator sharedInstance] IComMediator_RedPacketPasswordViewController:nil];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)inputViewResignFirstResponder {
    [self.redPacketInputView.inputTextField resignFirstResponder];
    [self.amountInputView.inputTextField resignFirstResponder];
    [self.messageInputView.inputTextView resignFirstResponder];
}

#pragma mark - event response

- (void)leftButtonAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)segmentedChanged:(UISegmentedControl *)sender {
    self.selectedSegmentIndex = sender.selectedSegmentIndex;
    if (sender.selectedSegmentIndex == 0) {
        self.redPacketPrompt.text = @"拼手气红包，每人抢到的红包金额随机";
        self.amountInputView.contentDict = @{@"left":@"总金额",
                                             @"right":@"工分"};
    }else {
        self.redPacketPrompt.text = @"普通红包，每人抢到的红包金额固定";
        self.amountInputView.contentDict = @{@"left":@"单个金额",
                                             @"right":@"工分"};
    }
    NSString *totalPoint = [self getTotalPoint:self.selectedSegmentIndex];
    self.totalWorkPoint.attributedText = [self showWorkPoint:totalPoint];
}

- (void)sendRedPacketBtnClicked:(UIButton *)sender {
    [self inputViewResignFirstResponder];
    if ([self.amountInputView.inputTextField.text intValue] < [self.redPacketInputView.inputTextField.text intValue]) {
        [MBProgressHUD showError:@"总金额必须大于红包个数"];
        return;
    }
    
    WEAKSELF
    [MBProgressHUD showProcessingActivityView:self.view];
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId};
    // 检查红包密码是否已设置
    [[ICRedPacketNetworkManager sharedInstance] checkRedPacketPasswordWithParam:param success:^(id object) {
        //[MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if ([[object objectForKey:@"data"] intValue] == 1) { //已设置
            weakSelf.payPasswordView = [[ICRedPacketPayPasswordView alloc] init];
            weakSelf.payPasswordView.totalPoint = [weakSelf getTotalPoint:weakSelf.selectedSegmentIndex];
            weakSelf.payPasswordView.delegate = weakSelf;
            [weakSelf.payPasswordView showInView:App_RootCtr.view];
        }else if ([[object objectForKey:@"data"] intValue] == 0) { //未设置
            [weakSelf pushToRedPacketPasswordViewController];
        }
    } failure:^(NSError *error) {
       // [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:error.domain];
    }];
}

#pragma mark - ICRedPacketPayPasswordViewDelegate
// 忘记密码
- (void)forgetPWDBtnClicked {
    [self.payPasswordView close];
    [self pushToRedPacketPasswordViewController];
}
// 确认
- (void)doneBtnClicked:(NSString *)password {
    if ([self getPasswordErrorCount] >= 3) {
        [self forgetPWDBtnClicked];
        return;
    }
    
    WEAKSELF
    int number = [self.redPacketInputView.inputTextField.text intValue];
    NSString *totalPoint = [self getTotalPoint:self.selectedSegmentIndex];
    NSString *message = self.messageInputView.inputTextView.text;
    NSString *placeholder = self.messageInputView.inputTextView.placeholder;
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [MBProgressHUD showProcessingActivityView:window];
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"type":[NSNumber numberWithInt:(int)self.selectedSegmentIndex+2], //2: 手气红包，3: 普通红包
                            @"gId":self.groupId,
                            @"count":[NSNumber numberWithInt:number],
                            @"sum":[NSNumber numberWithString:totalPoint],
                            @"message":message.length > 0 ? message : placeholder,
                            @"password":password};
    // 发送红包
    [[ICRedPacketNetworkManager sharedInstance] sendRedPacketWithParam:param success:^(id object) {
       // [MBProgressHUD hideAllHUDsForView:window animated:YES];
        [MBProgressHUD hideHUDForView:window animated:YES];
        weakSelf.model = [ICSendRedPacketModel mj_objectWithKeyValues:[object objectForKey:@"data"]];
        [weakSelf.payPasswordView close];
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationSendRedPacketNotification object:weakSelf.model];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:window animated:YES];
        //[MBProgressHUD hideAllHUDsForView:window animated:YES];
        if (error.code == 1100) { //密码错误
            [weakSelf savePasswordErrorCount];
            [weakSelf.payPasswordView clearThePassword];
            [MBProgressHUD showError:@"密码错误"];
        }else if (error.code == 8100) { //工分不足
            [MBProgressHUD showError:@"工分不足"];
        }else {
            [MBProgressHUD showError:error.domain];
        }
    }];
}

- (void)savePasswordErrorCount {
    NSInteger count = [self getPasswordErrorCount]+1;
    [[NSUserDefaults standardUserDefaults] setInteger:count forKey:@"passwordErrorCount"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSInteger)getPasswordErrorCount {
    NSInteger passwordErrorCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"passwordErrorCount"];
    return passwordErrorCount;
}

#pragma mark - Getter

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (UISegmentedControl *)segmentedControl {
    if (!_segmentedControl) {
        NSArray *items = @[@"拼手气红包", @"普通红包"];
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
        _segmentedControl.selectedSegmentIndex = 0;
        _segmentedControl.tintColor = ICRGB(0xe44e4e);
        [_segmentedControl addTarget:self action:@selector(segmentedChanged:) forControlEvents:UIControlEventValueChanged];
        [self.scrollView addSubview:_segmentedControl];
    }
    return _segmentedControl;
}

- (ICRedPacketInputView *)redPacketInputView {
    if (!_redPacketInputView) {
        _redPacketInputView = [[ICRedPacketInputView alloc] init];
        _redPacketInputView.inputTextField.placeholder = @"填写个数";
        _redPacketInputView.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
        [self.scrollView addSubview:_redPacketInputView];
    }
    return _redPacketInputView;
}

- (ICRedPacketInputView *)amountInputView {
    if (!_amountInputView) {
        _amountInputView = [[ICRedPacketInputView alloc] init];
        _amountInputView.inputTextField.placeholder = @"总金额必须大于红包个数";
        _amountInputView.inputTextField.keyboardType = UIKeyboardTypeNumberPad;
        [self.scrollView addSubview:_amountInputView];
    }
    return _amountInputView;
}

- (ICRedPacketInputView *)messageInputView {
    if (!_messageInputView) {
        _messageInputView = [[ICRedPacketInputView alloc] init];
        _messageInputView.inputTextView.placeholder = @"节节高升，再创佳绩!";
        [self.scrollView addSubview:_messageInputView];
    }
    return _messageInputView;
}

- (UILabel *)redPacketPrompt {
    if (!_redPacketPrompt) {
        _redPacketPrompt = [[UILabel alloc] init];
        _redPacketPrompt.font = ICFont(11.0 * Level);
        _redPacketPrompt.text = @"拼手气红包，每人抢到的红包金额随机";
        _redPacketPrompt.textColor = ICRGB(0x999999);
        _redPacketPrompt.textAlignment = NSTextAlignmentCenter;
        [self.scrollView addSubview:_redPacketPrompt];
    }
    return _redPacketPrompt;
}

- (UILabel *)peoplePrompt {
    if (!_peoplePrompt) {
        _peoplePrompt = [[UILabel alloc] init];
        _peoplePrompt.font = ICFont(11.0 * Level);
        _peoplePrompt.textColor = ICRGB(0x999999);
        [self.scrollView addSubview:_peoplePrompt];
    }
    return _peoplePrompt;
}

- (UILabel *)totalWorkPoint {
    if (!_totalWorkPoint) {
        _totalWorkPoint = [[UILabel alloc] init];
        _totalWorkPoint.attributedText = [self showWorkPoint:@"0.00"];
        _totalWorkPoint.textAlignment = NSTextAlignmentCenter;
        [self.scrollView addSubview:_totalWorkPoint];
    }
    return _totalWorkPoint;
}

- (UIButton *)sendButton {
    if (!_sendButton) {
        _sendButton = [[UIButton alloc] init];
        [_sendButton setTitle:@"发送红包" forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor colorWithWhite:1.0 alpha:0.4] forState:UIControlStateNormal];
        _sendButton.titleLabel.font = ICFont(17.0 * Level);
        [_sendButton setBackgroundImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_my_redpacket_done"] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(sendRedPacketBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:_sendButton];
        _sendButton.enabled = NO;
    }
    return _sendButton;
}

- (UILabel *)bottomPrompt {
    if (!_bottomPrompt) {
        _bottomPrompt = [[UILabel alloc] init];
        _bottomPrompt.textAlignment = NSTextAlignmentCenter;
        _bottomPrompt.text = @"未领取的红包，将于24小时后退回";
        _bottomPrompt.textColor = ICRGB(0x828282);
        _bottomPrompt.font = ICFont(14.0 * Level);
        [self.scrollView addSubview:_bottomPrompt];
    }
    return _bottomPrompt;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
